<template>
  <VPage class="h-[100%]">
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <XForm :fieldList="fieldList" :formOption="dict" :formData="form">
          <template #queryNo="{ input, value }">
            <VBatchInput
              @update:model-value="input"
              :model-value="value"
              placeholder="订单号/跟踪号"
              class="w-60"
              @search="query"
            />
          </template>
          <template #platform="{ input, value }">
            <PlatformSelect
              @update:model-value="input"
              :model-value="value"
              class="w-[240px]"
              multiple
            />
          </template>
          <template #shop="{ input, value }">
            <ShopSelect
              @update:model-value="input"
              :model-value="value"
              class="w-[240px] select-wrapper-style"
              multiple
              collapseTags
            />
          </template>
        </XForm>
        <teleport v-if="demandTabsLoad" to="#demand-tabs">
          <el-tabs v-model="form.sys_status" @tab-change="tabChange">
            <template v-for="(item) in tabs" :key="item">
              <el-tab-pane :name="item.value">
                <template #label>
                  {{ item.label }}(<span
                    :class="
                      tabValue == item.value
                        ? 'base-text-color'
                        : 'text-[var(--other-color-9)]'
                    "
                    >{{ item.count }}</span
                  >)
                </template>
              </el-tab-pane>
            </template>
          </el-tabs>
        </teleport>
      </template>
      <template #toolbar_btns>
        <div
          id="demand-tabs"
          class="w-full"
          v-dom-load="() => (demandTabsLoad = true)"
        ></div>
        <VActionBar :actions="actions" />
      </template>
      <template #operation="{ row }">
        <el-button
          link
          type="primary"
          @click="handleLocus(row)"
          v-hasPermi="[logisticsManageAuthList.track_packageno.details]"
        >
          详情
        </el-button>
      </template>
    </VTable>
    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
    <LogisticsDetailsDialog
      v-model="detailVisible"
      :data="selectItem"
      @close="selectItem = null"
    />
  </VPage>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import XForm from "@/components/XForm/index.vue";
import PlatformSelect from "@/components/PlatformSelect/index.vue";
import ShopSelect from "@/components/ShopSelect/index.vue";
import DerivedCenter from "@/components/DerivedCenter";
import { config_name } from "@/config/export.js";
import LogisticsDetailsDialog from "@/views/logistics-manage/track-package/components/LogisticsDetailsDialog/index.vue";
import { getChannelList, logisticsList } from "@/api/index.js";
import { trackPull, trackPackageNoList } from "./api";
import { getTableSelectRow } from "@/hooks/tool.js";
import { logisticsManageAuthList } from "@/Auth/logistics-manage.js";
import VBatchInput from '@/componentsPublic/BatchInput/index.vue'
const demandTabsLoad = ref(false);
const tableRef = ref();
const tabs = ref([]);
const publicStyle = { style: { width: "240px" } };
const fieldList = [
  {
    field: "logistics_id",
    ...publicStyle,
    type: "select",
    options: {
      placeholder: "服务商选择",
      labelKey: "logistics_name",
      valueKey: "logistics_id",
    },
    collapseTags: true,
    multiple: true,
    originOption: "logistics",
    class: "select-wrapper-style",
  },
  {
    field: "dateRange",
    placeholder: "发货时间",
    type: "dateTimeRange",
    itemProps: {
      startPlaceholder: "发货最早时间",
      endPlaceholder: "发货最晚时间",
    },
  },
  {
    field: "query_no",
    slot: "queryNo",
  },
  {
    field: "channel_id",
    type: "select",
    originOption: "channel",
    ...publicStyle,
    options: {
      placeholder: "渠道名称",
      labelKey: "channel_name",
      valueKey: "channel_id",
    },
    collapseTags: true,
    multiple: true,
    class: "select-wrapper-style",
  },
  {
    field: "platform_id",
    slot: "platform",
  },
  {
    field: "shop_id",
    slot: "shop",
  },
];

const tableOptins = reactive({
  formConfig: {
    data: {
      sys_status: "",
      dateRange: { type: "create_time", value: [], range: false }, // 组合+日期范围
    },
  },
  tooltipConfig: {
    showAll: false,
  },
  isToggle: true,
  columns: [
    { fixed: "left", width: 50, type: "checkbox" },
    {
      fixed: "left",
      minWidth: 200,
      title: "快递单号",
      field: "tracking_number",
    },
    { title: "渠道名称", minWidth: 200, field: "chanel_name" },
    { title: "服务商", minWidth: 200, field: "logistics_name" },
    { title: "发货国家", width: 100, field: "shipping_country" },
    {
      title: "目的地国家",
      width: 100,
      field: "destination_country",
    },
    {
      title: "系统运输状态",
      width: 200,
      field: "sys_status_name",
    },
    {
      title: "服务商运输状态",
      width: 200,
      field: "api_status_name",
    },
    { title: "订单号", width: 200, field: "customer_order_no" },
    { title: "最近抓取时间", width: 200, field: "api_last_time" },
    { title: "添加时间", width: 200, field: "create_time" },
    { title: "运输时间", width: 200, field: "delivery_time" },

    {
      title: "操作",
      minWidth: 100,
      fixed: "right",
      slots: { default: "operation" },
    },
  ],
  proxyConfig: {
    props: {
      result: "data",
      total: "total",
    },
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => {
        return trackPackageNoList({ ...form, ...page }).then((res) => {
          tabs.value = res?.data?.sys_status_counts || [];
          return {
            data: res?.data?.body || [],
            total: res.total,
          };
        });
      },
    },
  },
});

const query = () => {
  tableRef?.value.query();
};
const handleCrawl = async () => {
  let rows = tableRef.value?.$table.getCheckboxRecords();
  if (!rows?.length) return ElMessage.warning("请至少选择一条数据!");
  const id = rows.map((n) => n.id);
  // const tracking_number = rows.map((n) => n.tracking_number).filter((v) => !!v);
  try {
    const { code, message } = await trackPull({
      id,
    });
    if (code !== 200) {
      ElMessage.warning(message);
      return;
    }
    ElMessage.success("操作成功");
    query();
  } catch (e) {
    console.error(e);
  }
};

const tabValue = ref("");
const tabChange = (name) => {
  tabValue.value = name;
  query();
};
//导出中心
const DerivedCenterRef = ref();
const handleExport = () => {
  let condition = getTableSelectRow(tableRef.value);
  DerivedCenterRef.value?.open({
    tag_name: config_name["logistics_manage"]["quick_order"],
    condition,
  });
};

const detailVisible = ref(false);
const selectItem = ref();
const handleLocus = (item) => {
  selectItem.value = item;
  detailVisible.value = true;
};
const dict = reactive({});
//获取物流商
const getlogistics = () => {
  logisticsList({}).then((res) => {
    dict.logistics = res?.data || [];
  });
};
getlogistics();
const getChannel = async () => {
  const { data } = await getChannelList();
  dict.channel = data;
};
getChannel();
const actions = [
  {
    label: "手动抓取",
    type: "primary",
    fn: handleCrawl,
    permission: [logisticsManageAuthList.track_packageno.take],
  },
  {
    label: "导出",
    right: true,
    dkicon: "icon-Upload",
    fn: handleExport,
    permission: [logisticsManageAuthList.track_packageno.export],
  },
];
</script>
<style lang="scss" scoped>
.tabs {
  width: 100%;
  .el-tabs__item {
    color: var(--other-color-9);
  }
}
:deep(.vxe-buttons--wrapper) {
  width: 100%;
}
</style>
